package com.demo.bmsconsole;

/*
 * Main BMS Console program for initializing all top-level objects.
 * Currently, also manages screens. 
 * TODO: Create Screen Manager class.
 * 
 */

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.demo.bmsconsole.State.EMajor;

public class BMSconsole extends Activity {
    /** Called when the activity is first created. */
	public static final int ADB_PORT = 6699;
	private static String TAG;
	private static Context mCtx;
	
	private static ProgressBar mStartProgress;
	private static Button mStartButton;
	private static Button mChargeButton;
	private static TextView mLogView;
	private static ScrollView mScrollView;
	
	@SuppressWarnings("unused")
	private int mCurrentView;
	private static ToggleButton mCurrentReadyRadio;
	private static Handler mHandler = new Handler();
	private ToggleButton mCurrentGoRadio;
    private Animation mAnimation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible

    private static final int SCROLL_MANUAL = Menu.FIRST + 1;
	private static final int SCROLL_AUTO = Menu.FIRST + 2;
	private static boolean mScrollAuto = true;

    @Override
    public void onCreate(Bundle savedInstanceState)
	{
        super.onCreate(savedInstanceState);
        TAG = getPackageName();
        mCtx = this;
        
        // now set up start view
        setStartView(true);

	    // initialize: set up animation, etc
        initialize();

        // Set global state
        State.setMajorState(EMajor.Init);
  	}

	private void initialize()
	{
	    mAnimation.setDuration(1000); // duration in millisecs.
	    mAnimation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
	    mAnimation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
	    mAnimation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back	

	    new LogFile(this);

	    BMSdb.getSingleton(this);
		
		new Config(this);
		new State(this);
		new Interpreter(this);

		new ADBServer(this,ADB_PORT);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case SCROLL_MANUAL:
			mScrollAuto = false;
			break;
		case SCROLL_AUTO:
			mScrollAuto  = true;
			break;
		}
		return super.onContextItemSelected(item);

	}

	@Override
	public void onPause()
	{
		super.onPause();
	}
	
	@Override
	public void onDestroy()
	{
		ADBServer.stop();
		try {
			LogFile.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		super.onDestroy();
	}

	public static void log(String s) {
		mLogView.append(s);
	}

	// Need to move this to view manager.
	public static void initComplete(boolean noErrors) {
		mLogView.append(mCtx.getString(R.string.start_done_checking));
		mStartProgress.setVisibility(ProgressBar.GONE);
		if (noErrors) {
			mStartButton.setVisibility(View.VISIBLE);
			mChargeButton.setVisibility(View.VISIBLE);
		} else {
			// TODO initiate recovery by prompting user.
		}
	}
	
	private void setStartView(boolean firstTime) {
		Log.d(TAG,"at start");

		setContentView(R.layout.start);
        mStartProgress = (ProgressBar)findViewById(R.id.startProgress);
        mStartButton = (Button) findViewById(R.id.startButton);
        mChargeButton = (Button) findViewById(R.id.chargeButton);
        mStartButton.setSoundEffectsEnabled(true);
        mLogView = (TextView)findViewById(R.id.logCmd);
	    mScrollView = (ScrollView)findViewById(R.id.start_scrollLog);

		registerForContextMenu(mLogView);
        mStartButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mStartButton.playSoundEffect(SoundEffectConstants.CLICK);
            	setReadyView();
            }
        });
 
        if (firstTime) {
        	mStartButton.setVisibility(View.INVISIBLE);
        	mChargeButton.setVisibility(View.INVISIBLE);
        } else {
        	mStartProgress.setVisibility(ProgressBar.GONE);
        }
    }
	
	private void setGoView() {
		setContentView(R.layout.go);
		ToggleButton left = (ToggleButton)findViewById(R.id.leftTurnRadio);
		ToggleButton right = (ToggleButton)findViewById(R.id.rightTurnRadio);
		
		Button horn = (Button)findViewById(R.id.hornButton);
		/*
		horn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				arduinoHorn(true);
			}
		});
		*/		
		horn.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN)
					arduinoHorn(true);
				else if (event.getAction() == MotionEvent.ACTION_UP) 
					arduinoHorn(false);
				return false;
			}
		});
		Button back = (Button)findViewById(R.id.backButton);
		Button home = (Button)findViewById(R.id.homeButton);
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setReadyView();				
			}
		});
		home.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// already at go view.
				// setView(R.layout.go);				
			}
		});
		mCurrentGoRadio = null;
		
		left.setChecked(false);
		right.setChecked(false);
		OnClickListener radioListener = new View.OnClickListener() {
			public void onClick(View v) {
				selectGoRadio(v);
			}};
			
		// set listeners.
		left.setOnClickListener(radioListener);
		right.setOnClickListener(radioListener);
	}

	protected void arduinoHorn(boolean on) {
		final String hornPin = BMSdb.getConfigValue(BMSdb.CFG_HORN);
		// TODO: need to move config to initialization.
		final String cfg = "<pc> " + hornPin + " o";
		final String hornOn = "<ph> " + hornPin;
		final String hornOff = "<pl> " + hornPin;
		if (on) {
			ADBServer.send(cfg);
			ADBServer.send(hornOn);
		} else {
			ADBServer.send(hornOff);
		}
	}
	
	protected void selectGoRadio(View v) {
		final ToggleButton rb = (ToggleButton)v;
		mHandler.post(new Runnable() {
			public void run() {
				if (rb.equals(mCurrentGoRadio)) {
					rb.setChecked(false);
					rb.clearAnimation();
					mCurrentGoRadio = null;
				} else {
					if (mCurrentGoRadio != null) {
						mCurrentGoRadio.setChecked(false);
						mCurrentGoRadio.clearAnimation();
					}
					mCurrentGoRadio = rb;
					mCurrentGoRadio.setChecked(true);
					mCurrentGoRadio.startAnimation(mAnimation);
				}
			}
		});
		
	}
	private void setReadyView() {
		setContentView(R.layout.ready);
		ToggleButton fwd1 = (ToggleButton)findViewById(R.id.fwd1Radio);
		ToggleButton neutral = (ToggleButton)findViewById(R.id.neutralRadio);
		ToggleButton fwd2 = (ToggleButton)findViewById(R.id.fwd2Radio);
		ToggleButton reverse = (ToggleButton)findViewById(R.id.reverseRadio);
		Button go = (Button)findViewById(R.id.goButton);
		go.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setGoView();
			}
		});
		Button back = (Button)findViewById(R.id.backButton);
		Button home = (Button)findViewById(R.id.homeButton);
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setStartView(false);				
			}
		});
		home.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setGoView();				
			}
		});
		mCurrentReadyRadio = neutral;
		mCurrentReadyRadio.setChecked(true);
//		mCurrentReadyRadio.setButtonDrawable(R.color.green);
		
		fwd1.setChecked(false);
		fwd2.setChecked(false);
		reverse.setChecked(false);
		OnClickListener radioListener = new View.OnClickListener() {
			public void onClick(View v) {
				selectReadyRadio(v);
			}};
			
		// set listeners.
		fwd1.setOnClickListener(radioListener);
		fwd2.setOnClickListener(radioListener);
		neutral.setOnClickListener(radioListener);
		reverse.setOnClickListener(radioListener);
	}

	private void selectReadyRadio(View v) {
		final ToggleButton rb = (ToggleButton)v;
		mHandler.post(new Runnable() {
			public void run() {
				mCurrentReadyRadio.setChecked(false);
				mCurrentReadyRadio = rb;
				mCurrentReadyRadio.setChecked(true);
			}
		});
	}

	
}